#!/usr/bin/env python
# encoding: utf-8
"""
test.py

Created by  on 2008-10-19.
Copyright (c) 2008 __MyCompanyName__. All rights reserved.
"""

import sys
import os
import traceback
from Foundation import *

ERROR = 0
INFO = 1
DEBUG = 2
LOGLEVEL = 2

class MacLog(object):
	
	def clog(self,msg):
		if LOGLEVEL>=INFO:
			NSLog(unicode(msg))

	def cdebug(self,msg):
		if LOGLEVEL>=DEBUG:
			NSLog(unicode(msg))

	def cerr(self,msg):
		if LOGLEVEL>=ERROR:
			NSLog(unicode(msg))



def n2py(ndata):
	#print type(ndata)
	return ndata
	
def py2n(data):
	#print type(data)
	result = data
	if type(data) is dict:
		#print 'Transforming dict'
		result = NSMutableDictionary.dictionary()
		for key in data:
			result[key]=py2n(data[key])
		
	return result
def loadData(filename):
	filename = os.path.expanduser(filename)
	data = {}
	try:
		data =  NSMutableDictionary.dictionaryWithContentsOfFile_(filename)
	except:
		err ="\n".join(traceback.format_exception(*sys.exc_info()))
		print 'io error' , err
	return n2py(data)
		
def saveData(filename,data):
	filename = os.path.expanduser(filename)
	ndata =  py2n(data)
	
	dname = os.path.dirname(filename)
	#print dname
	try:
		if not os.path.exists(dname):
			print 'Try to create folder'
			os.makedirs(dname)
		if not ndata.writeToFile_atomically_(filename, True):
			print 'Cannot save to file'
			return False
		return True
	except:
		err ="\n".join(traceback.format_exception(*sys.exc_info()))
		print 'Io error' , err
		return False

if __name__ == '__main__':
	data = {'good':False,'name':'Peterke','Age':8,'things':['car','laptop']}
	print saveData('~/test.txt',data)
	data = loadData('~/test.txt')
	print data
	
